__author__ = 'jlin@systemsbiology.org'
import os
import sys
import seqhash_def
#from poster.encode import multipart_encode
#from poster.streaminghttp import register_openers
#import urllib2
#try: import json #python 2.6 included simplejson as json
#except ImportError: import simplejson as json

seqhash = seqhash_def.getseqhash()

#seqhash["YMULTI_RAD_1"] = "YSEQ8"
#seqhash["YMULTI_RAD_29"] = "YSEQ38"
bchash = {}
#read in barcode file and store in hash

def loadBarcodeKeyHash():
	keyfile = open("./radbc_4.tsv")
	for line in keyfile:
		keyValue = line.split("\t")
		bchash[keyValue[0]] = keyValue[1].rstrip('\n\r')


def parse2UpdateSql(csvfile):
	loadBarcodeKeyHash()
	csv = open(csvfile)
	csvname = csv.name.split(".")[0]
	print "csvname:" + csvname
	sqlfile = open(csvname + ".sql", "w")
#update omics_samples set barcode = 'AATT' where omics_key = 'YSEQ10' and strains = 'YPG_529'; 
	for line in csv:
		#print line
		splitted = line.split(",")
		updateStr = "update omics_samples set barcode = '" + bchash[splitted[3].rstrip('\n\r')] +  "', strains ='" + splitted[2].replace(" ", "_") + "' where omics_key = '" + seqhash[csvname] + "' and strains = '" + splitted[2].replace(" ", " ").rstrip("\n\r") + "';" 
		#updateStr = "update omics_samples set barcode = '" + bchash[splitted[3].rstrip('\n\r')]  + "' where omics_key = '" + seqhash[csvname] + "' and strains = '" + splitted[2].replace(" ", "_").replace("YPG","YPG_").rstrip("\n\r") + "';"
		#INSERT INTO omics_samples (omics_key, omics_type, project, status, strains, key_meta, barcode) VALUES ('YSEQ31', 'NGS', 'Dudley Paired End', 'completed', 'YPGX', '62GEWAAXX:8', 'AACC');
		insertStr = "INSERT INTO omics_samples (omics_key, omics_type, project, status, strains, key_meta, barcode) VALUES ('" + seqhash[csvname] + "', 'NGS', 'Dudley NV Multiplexed RAD', 'completed', '" + splitted[2].replace(" ", "_").rstrip("\n\r") + "', '622YMAAXX:2', '" + bchash[splitted[3].rstrip('\n\r')] + "');"
		sqlfile.write(updateStr + "\n");
		print updateStr
	sqlfile.close()
	csv.close()	

if __name__ == "__main__":
        #Read in config
        #config = ConfigParser.RawConfigParser()
        #config.read('./cgs_lims.config')
        parse2UpdateSql(sys.argv[1])

